package com.bw.kf.playvideo

import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.common.mvi.NetworkResult
import com.example.common.room.CommentDraftRepository
import com.example.common.room.VideoDatabase
import com.example.common.room.VideoRepository
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import org.jash.playvideo.R
import org.jash.playvideo.databinding.DialogCommentsBinding
import java.text.SimpleDateFormat
import java.util.*

class CommentsDialog(
    context: Context,
    private val videoId: Int,
    private val videoRepository: VideoRepository,
    private val onCommentAdded: (CommentEntityItem) -> Unit = {}
) : Dialog(context, R.style.FullScreenDialog) {
    
    companion object {
        // 最大评论层级（0-3，共4级）
        private const val MAX_LEVEL = 3
    }

    private lateinit var binding: DialogCommentsBinding
    private lateinit var commentAdapter: CommentAdapter
    private val comments = mutableListOf<CommentEntityItem>()
    private val dateFormat = SimpleDateFormat("MM-dd HH:mm", Locale.getDefault())
    private val commentRepository = CommentRepository()
    private lateinit var draftRepository: CommentDraftRepository
    private val dialogScope = CoroutineScope(Dispatchers.Main + SupervisorJob())
    
    // 回复相关状态
    private var replyToComment: CommentEntityItem? = null
    private var isReplying = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DialogCommentsBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        // 设置全屏对话框
        window?.setLayout(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.MATCH_PARENT
        )
        
        // 初始化评论草稿仓库
        val database = VideoDatabase.getDatabase(context)
        draftRepository = CommentDraftRepository(database.commentDraftDao())
        
        setupViews()
        loadComments()
        
        // 恢复草稿
        loadCommentDraft()
    }

    private fun setupViews() {
        // 设置RecyclerView
        commentAdapter = CommentAdapter(
            comments = comments,
            onLikeClick = { comment ->
                handleCommentLike(comment)
            },
            onReplyClick = { comment ->
                startReply(comment)
            }
        )
        
        binding.rvComments.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = commentAdapter
        }
        
        // 发送按钮点击事件
        binding.btnSend.setOnClickListener {
            val content = binding.etComment.text.toString().trim()
            if (content.isNotEmpty()) {
                if (isReplying && replyToComment != null) {
                    sendReply(content, replyToComment!!)
                } else {
                    sendComment(content)
                }
                binding.etComment.text.clear()
                cancelReply()
                // 删除草稿（评论已发送）
                deleteDraft()
            } else {
                Toast.makeText(context, "请输入评论内容", Toast.LENGTH_SHORT).show()
            }
        }
        
        // 关闭按钮
        binding.ivClose.setOnClickListener {
            // 检查是否有未发送的评论内容
            val commentText = binding.etComment.text.toString().trim()
            if (commentText.isNotEmpty()) {
                // 显示确认对话框
                AlertDialog.Builder(context)
                    .setTitle("提示")
                    .setMessage("您有未发送的评论内容，确定要离开吗？")
                    .setPositiveButton("保留并离开") { _, _ ->
                        // 保存评论内容到数据库
                        saveCommentDraft(commentText)
                        dismiss()
                    }
                    .setNegativeButton("放弃") { _, _ ->
                        // 删除草稿
                        deleteDraft()
                        dismiss()
                    }
                    .setNeutralButton("取消", null)
                    .show()
            } else {
                dismiss()
            }
        }
    }

    private fun loadComments() {
        dialogScope.launch {
            commentRepository.getComments(0, videoId.toString()).collect { result ->
                when (result) {
                    is NetworkResult.Loading -> {
                        // 显示加载中状态
                    }
                    is NetworkResult.Success -> {
                        // 更新评论列表
                        updateComments(result.data.data)
                    }
                    is NetworkResult.Error -> {
                        Toast.makeText(context, "加载评论失败: ${result.exception.message}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }
    }

    private fun sendComment(content: String) {
        dialogScope.launch {
            commentRepository.sendComment(0, videoId.toString(), content).collect { result ->
                when (result) {
                    is NetworkResult.Loading -> {
                        // 显示发送中状态
                    }
                    is NetworkResult.Success -> {
                        result.data.data?.let { newComment ->
                            // 添加到适配器，确保在对话框中显示
                            commentAdapter.addComment(newComment)
                            
                            // 不再通知Activity添加评论，避免重复添加
                            // onCommentAdded(newComment)
                            
                            Toast.makeText(context, result.data.msg, Toast.LENGTH_SHORT).show()
                        }
                    }
                    is NetworkResult.Error -> {
                        Toast.makeText(context, "评论发送失败: ${result.exception.message}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }
    }

    private fun sendReply(content: String, parentComment: CommentEntityItem) {
        dialogScope.launch {
            // 计算回复的层级
            val replyLevel = when {
                // 如果是回复主评论，层级为1
                parentComment.parentId == null -> 1
                // 如果回复的是已经是3级评论，保持在3级
                parentComment.level >= MAX_LEVEL -> MAX_LEVEL
                // 否则层级+1
                else -> parentComment.level + 1
            }
            
            // 确定根评论ID
            val rootCommentId = parentComment.rootCommentId ?: 
                               if (parentComment.parentId == null) parentComment.id else parentComment.parentId
            
            commentRepository.sendReply(
                datatype = 0, 
                itemid = videoId.toString(), 
                content = content, 
                parentId = parentComment.id,
                replyToUserId = parentComment.userid,
                replyToUserName = parentComment.nickname
            ).collect { result ->
                when (result) {
                    is NetworkResult.Loading -> {
                        // 显示发送中状态
                    }
                    is NetworkResult.Success -> {
                        result.data.data?.let { originalReply ->
                            // 创建新的回复对象，设置层级和根评论ID
                            val newReply = originalReply.copy(
                                level = replyLevel,
                                rootCommentId = rootCommentId
                            )
                            
                            // 添加到适配器，确保在对话框中显示
                            commentAdapter.addComment(newReply)
                            
                            // 不再通知Activity添加评论，避免重复添加
                            // onCommentAdded(newReply)
                            
                            Toast.makeText(context, result.data.msg, Toast.LENGTH_SHORT).show()
                        }
                    }
                    is NetworkResult.Error -> {
                        Toast.makeText(context, "回复发送失败: ${result.exception.message}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }
    }
    
    private fun saveCommentDraft(commentText: String) {
        dialogScope.launch {
            draftRepository.saveDraft(videoId, commentText)
        }
    }
    
    private fun loadCommentDraft() {
        dialogScope.launch {
            val draft = draftRepository.getDraftByVideoId(videoId)
            if (draft != null && draft.content.isNotEmpty()) {
                binding.etComment.setText(draft.content)
                binding.etComment.setSelection(draft.content.length)
            }
        }
    }
    
    private fun deleteDraft() {
        dialogScope.launch {
            draftRepository.deleteDraftByVideoId(videoId)
        }
    }

    private fun startReply(comment: CommentEntityItem) {
        replyToComment = comment
        isReplying = true
        
        // 更新UI显示回复状态
        binding.etComment.hint = "回复 ${comment.nickname}"
        binding.etComment.requestFocus()
        
        // 显示取消回复按钮
        binding.btnCancelReply.visibility = View.VISIBLE
        binding.btnCancelReply.setOnClickListener {
            cancelReply()
        }
    }

    private fun cancelReply() {
        replyToComment = null
        isReplying = false
        
        // 恢复UI
        binding.etComment.hint = "写评论..."
        binding.btnCancelReply.visibility = View.GONE
    }

    private fun handleCommentLike(comment: CommentEntityItem) {
        dialogScope.launch {
            commentRepository.likeComment(comment.id).collect { result ->
                when (result) {
                    is NetworkResult.Loading -> {
                        // 显示处理中状态
                    }
                    is NetworkResult.Success -> {
                        result.data.data?.let { updatedComment ->
                            // 更新评论的点赞状态
                            comment.isLiked = updatedComment.isLiked
                            comment.agreenum = updatedComment.agreenum
                            
                            // 刷新适配器
                            val position = comments.indexOf(comment)
                            if (position != -1) {
                                commentAdapter.notifyItemChanged(position)
                            }
                            
                            Toast.makeText(context, result.data.msg, Toast.LENGTH_SHORT).show()
                        }
                    }
                    is NetworkResult.Error -> {
                        Toast.makeText(context, "操作失败: ${result.exception.message}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }
    }
    
    /**
     * 更新评论列表
     */
    fun updateComments(newComments: List<CommentEntityItem>) {
        commentAdapter.updateComments(newComments)
        
        // 显示评论数量
        if (newComments.isNotEmpty()) {
            Toast.makeText(context, "已加载${newComments.size}条评论", Toast.LENGTH_SHORT).show()
        }
    }
    
    // 获取当前用户信息的方法
    private fun getCurrentUserId(): Int {
        return UserManager.getCurrentUserId()
    }
    
    private fun getCurrentUserName(): String {
        return UserManager.getCurrentUserName()
    }
    
    private fun getCurrentUserAvatar(): String {
        return UserManager.getCurrentUserAvatar()
    }
    
    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        dialogScope.cancel()
    }
}
